import { UIHEIGHT, UIWIDTH } from '@/constant/common'
import { useFullscreen } from 'ahooks'
import classNames from 'classnames'
import { debounce } from 'lodash-es'
import { useContext, useEffect, useRef, useState } from 'react'

import { LoginEnt } from '@/models/LoginEnt'
import { useAppSelector } from '@/redux/store'
import { loginEntSlice } from '@/redux/toolkitSlice/loginEntSlice'
import { useDispatch } from 'react-redux'

import WrapperHeader from '../BigScreenBase/Compoments/WrapperHeader'
import type { AssociationData } from '../BigScreenBase/interface'
import type { AlerMapRef } from './Center/AlerMap'
import AlerMap from './Center/AlerMap'
import CenterToDayWarn from './Center/CenterToDayWarn'
import LeftWarnData from './Left/LeftWarnData'
import LeftWarnTime from './Left/LeftWarnTime'
import RightSafeEdu from './Right/RightSafeEdu'
import RightSafeGovern from './Right/RightSafeGovern'
import { SwitchAndIntervalRef } from './interface'

import { useNavigate } from 'react-router-dom'
import '../BigScreenBase/module.less'
import BigScreenContext from '../Context/BigScreenContext'
import './index.less'

function BigScreenWarn() {
  const dispatch = useDispatch()
  const navigator = useNavigate()
  const {
    entId: initialEntId,
    entTypeCode,
    entName,
    regionCode,
    operateEntFlag,
    selectedEnt
  } = useAppSelector((state) => {
    // console.log('--state.loginEnt--:', state.loginEnt);
    return state.loginEnt
  })
  const entId =
    selectedEnt && selectedEnt.entId ? selectedEnt.entId : initialEntId
  // console.log('---2屏--entId--:', entId);
  const { onSlideToRight, onSlideToLeft } = useContext(BigScreenContext)
  const largeScreenContainer = useRef<HTMLDivElement>(null)
  const containerWrapperRef = useRef<HTMLDivElement>(null)
  const [domScale, setDomScale] = useState<number>(1)
  const timerRef = useRef<any>() //每隔5分钟刷新一次的定时器

  const LeftWarnDataCompRef = useRef<SwitchAndIntervalRef>(null)
  const LeftWarnTimeCompRef = useRef<SwitchAndIntervalRef>(null)
  const CenterToDayWarnCompRef = useRef<SwitchAndIntervalRef>(null)
  const RightSafeEduCompRef = useRef<SwitchAndIntervalRef>(null)
  const RightSafeGovernRef = useRef<SwitchAndIntervalRef>(null)

  const [weatherPlugin, setWeatherPlugin] = useState<any>()

  //全屏显示
  const [isFullscreen, { toggleFullscreen }] =
    useFullscreen(largeScreenContainer)
  const isFullscreenRef = useRef<boolean>(isFullscreen)

  //地图
  const AlerMapCompRef = useRef<AlerMapRef>(null)
  const [alerMapShowType, setAlerMapShowType] = useState<'heat' | 'poi'>('heat') //地图展现形式

  // 标题协会切换
  const [selectedAssociationItem, setSelectedAssociationItem] =
    useState<AssociationData>({
      key: entId,
      label: '',
      regionCode,
      operateEntFlag,
      regionCodeValue: ''
    })
  const selectedAssociationKeyRef = useRef<string>(entId)

  function _resizeCanvas() {
    // console.log('--resize图表--')
    if (RightSafeGovernRef.current) {
      RightSafeGovernRef.current?.resize?.()
    }
    if (AlerMapCompRef.current) {
      AlerMapCompRef.current.resize?.()
    }
    if (LeftWarnTimeCompRef.current) {
      LeftWarnTimeCompRef.current.resize?.()
    }
    if (RightSafeEduCompRef.current) {
      RightSafeEduCompRef.current.resize?.()
    }
    if (CenterToDayWarnCompRef.current) {
      CenterToDayWarnCompRef.current.resize?.()
    }
  }

  //大屏 等比缩放
  function _setWrapperSize(largeScreenDom: HTMLDivElement) {
    const { clientWidth, clientHeight } = largeScreenDom ?? {}
    if (!clientWidth || !clientHeight) {
      //切换页签时，clientWidth === 0，clientHeight===0
      setTimeout(() => {
        _setWrapperSize(largeScreenDom)
      }, 1000)
      return
    }

    let widthScale, heightScale

    if (isFullscreenRef.current) {
      widthScale = window.innerWidth / UIWIDTH
      heightScale = window.innerWidth / UIHEIGHT
    } else if (clientWidth && clientHeight) {
      widthScale = clientWidth / UIWIDTH
      heightScale = clientHeight / UIHEIGHT
    }

    const finalScale =
      widthScale && heightScale ? Math.min(widthScale, heightScale) : 1 //取小者，保持等比缩放，dom尺寸/内容不变形
    setDomScale(finalScale)
    containerWrapperRef.current!.style.width = UIWIDTH * finalScale + 'px'
    containerWrapperRef.current!.style.height = UIHEIGHT * finalScale + 'px'

    // containerWrapperRef.current!.style.transform = `scale(${finalScale}) translate(-50%, -50%)`
  }

  //全屏操作 也会触发window.resize()
  const debounceResize = debounce(() => {
    // console.log("--debounceResize--isFullscreen--:", isFullscreen)
    _setWrapperSize(largeScreenContainer.current!)
    _resizeCanvas()
  }, 500)

  useEffect(() => {
    isFullscreenRef.current = isFullscreen
    window.addEventListener('resize', debounceResize) //初始化的时候不执行
    return () => {
      window.removeEventListener('resize', debounceResize)
    }
  }, [isFullscreen])

  //协会切换
  const handleAssociationClick = (associationItem: AssociationData) => {
    const key = associationItem.key
    // console.log("--handleAssociationClick--key--:", key)
    if (selectedAssociationKeyRef.current === key) return
    dispatch(
      loginEntSlice.actions.updateSelectedEnt(
        new LoginEnt({
          ...associationItem,
          entId: key,
          entName: associationItem.label
        })
      )
    )
    clearTimer()

    setSelectedAssociationItem(associationItem)
    selectedAssociationKeyRef.current = key

    if (LeftWarnDataCompRef.current) {
      LeftWarnDataCompRef.current.switchAssociation(key)
    }
    if (LeftWarnTimeCompRef.current) {
      LeftWarnTimeCompRef.current.switchAssociation(key)
    }
    if (AlerMapCompRef.current) {
      AlerMapCompRef.current.switchAssociation(key)
    }
    if (CenterToDayWarnCompRef.current) {
      CenterToDayWarnCompRef.current.switchAssociation(key)
    }
    if (RightSafeEduCompRef.current) {
      RightSafeEduCompRef.current.switchAssociation(key)
    }
    if (RightSafeGovernRef.current) {
      RightSafeGovernRef.current.switchAssociation(key)
    }
  }

  const startTimer = () => {
    //开始
    if (timerRef.current) clearInterval(timerRef.current)
    // console.log("--触发--startTimer---")
    timerRef.current = setInterval(() => {
      if (LeftWarnDataCompRef.current) {
        LeftWarnDataCompRef.current.intervalRefresh()
      }

      if (LeftWarnTimeCompRef.current) {
        LeftWarnTimeCompRef.current.intervalRefresh()
      }
      if (AlerMapCompRef.current) {
        AlerMapCompRef.current.intervalRefresh()
      }
      if (CenterToDayWarnCompRef.current) {
        CenterToDayWarnCompRef.current.intervalRefresh()
      }
      if (RightSafeEduCompRef.current) {
        RightSafeEduCompRef.current.intervalRefresh()
      }
      if (RightSafeGovernRef.current) {
        RightSafeGovernRef.current.intervalRefresh()
      }
    }, 300000) //300s = 5分钟  300000
  }

  const clearTimer = () => {
    // console.log("--触发--clearTimer---")
    //清除
    if (timerRef.current) {
      clearTimeout(timerRef.current)
    }
  }

  useEffect(() => {
    if (!largeScreenContainer.current || !containerWrapperRef.current) return
    _setWrapperSize(largeScreenContainer.current)

    return () => {
      clearTimer()
    }
  }, [])

  //切换热力图/poi
  const handleSwitchAlerMapType = (
    event: React.MouseEvent,
    type: 'poi' | 'heat'
  ) => {
    event.stopPropagation()
    setAlerMapShowType(type)
    AlerMapCompRef.current?.switchAlerMapShowType(type)
  }

  return (
    <div className="large-screen-container-warn" ref={largeScreenContainer}>
      <div className="container-wrapper" ref={containerWrapperRef}>
        <AlerMap
          ref={AlerMapCompRef}
          onInitialWeatherPlugin={setWeatherPlugin}
          selectedAssociationItem={selectedAssociationItem}
          onClearTimer={clearTimer}
          onStartTimer={startTimer}
        />
        <WrapperHeader
          prevTitle="安全数据"
          nextTitle="治理成效"
          style={{ width: `${UIWIDTH}px`, transform: `scale(${domScale})` }}
          selectedAssociationItem={selectedAssociationItem}
          onAssociationClick={handleAssociationClick}
          gotoNext={() => {
            setTimeout(() => {
              navigator('/bigScreenGovern')
            }, 500)
            onSlideToLeft()
          }}
          gotoPrev={() => {
            setTimeout(() => {
              navigator('/bgBaseData')
            }, 500)
            onSlideToRight()
          }}
          weatherPlugin={weatherPlugin}
          name="数智治理"
          isFullscreen={isFullscreen}
          onToggleFullScreen={toggleFullscreen}
        />
        <div
          className="wrapper-left-scale"
          style={{
            left: `${8 * domScale}px`,
            top: `${104 * domScale}px`,
            transform: `scale(${domScale})`
          }}
        >
          <LeftWarnData
            onClearTimer={clearTimer}
            onStartTimer={startTimer}
            ref={LeftWarnDataCompRef}
            selectedAssociationItem={selectedAssociationItem}
          />
          <LeftWarnTime
            ref={LeftWarnTimeCompRef}
            selectedAssociationItem={selectedAssociationItem}
            onClearTimer={clearTimer}
            onStartTimer={startTimer}
          />
        </div>

        <div
          className="wrapper-center-section1-scale"
          style={{
            top: `${104 * domScale}px`,
            right: `${478 * domScale}px`,
            transform: `scale(${domScale})`
          }}
        >
          <p
            className={classNames({ ['selected']: alerMapShowType === 'heat' })}
            onClick={(event) => {
              handleSwitchAlerMapType(event, 'heat')
            }}
          >
            热力
          </p>
          <p
            className={classNames({ ['selected']: alerMapShowType === 'poi' })}
            onClick={(event) => {
              handleSwitchAlerMapType(event, 'poi')
            }}
          >
            POI
          </p>
        </div>

        <div
          className="wrapper-center-section2-scale"
          style={{
            bottom: `${16 * domScale}px`,
            left: `${478 * domScale}px`,
            transform: `scale(${domScale})`
          }}
        >
          <CenterToDayWarn
            ref={CenterToDayWarnCompRef}
            selectedAssociationItem={selectedAssociationItem}
          />
        </div>

        <div
          className="wrapper-right-scale"
          style={{
            right: `${8 * domScale}px`,
            top: `${104 * domScale}px`,
            transform: `scale(${domScale})`
          }}
        >
          <RightSafeGovern
            ref={RightSafeGovernRef}
            selectedAssociationItem={selectedAssociationItem}
          />
          <RightSafeEdu
            ref={RightSafeEduCompRef}
            selectedAssociationItem={selectedAssociationItem}
            onClearTimer={clearTimer}
            onStartTimer={startTimer}
          />
        </div>
      </div>
    </div>
  )
}

export default BigScreenWarn
